package com.google.firebase.quickstart.database.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.quickstart.DemoApplication;
import com.google.firebase.quickstart.database.R;
import com.google.firebase.quickstart.database.common.data.model.Dialog;
import com.google.firebase.quickstart.database.common.data.model.User;
import com.google.firebase.quickstart.database.custom.holder.CustomHolderMessagesActivity;
import com.google.firebase.quickstart.database.viewholder.UserViewHolder;

public abstract class UsersListFragment extends Fragment {

    private static final String TAG = "UsersListFragment";

    // [START define_database_reference]
    private DatabaseReference mDatabase;
    // [END define_database_reference]

    private FirebaseRecyclerAdapter<User, UserViewHolder> mAdapter;
    private RecyclerView mRecycler;
    private LinearLayoutManager mManager;

    public UsersListFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View rootView = inflater.inflate(R.layout.fragment_users, container, false);

        // [START create_database_reference]
        mDatabase = FirebaseDatabase.getInstance().getReference();
        // [END create_database_reference]
        mRecycler = rootView.findViewById(R.id.messages_list);
        mRecycler.setHasFixedSize(true);

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Set up Layout Manager, reverse layout
        mManager = new LinearLayoutManager(getActivity());
        mManager.setReverseLayout(true);
        mManager.setStackFromEnd(true);
        mRecycler.setLayoutManager(mManager);

        // Set up FirebaseRecyclerAdapter with the Query
        Query postsQuery = getQuery(mDatabase);

        FirebaseRecyclerOptions options = new FirebaseRecyclerOptions.Builder<User>()
                .setQuery(postsQuery, User.class)
                .build();

        mAdapter = new FirebaseRecyclerAdapter<User, UserViewHolder>(options) {

            @Override
            public UserViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
                LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
                return new UserViewHolder(inflater.inflate(R.layout.item_users, viewGroup, false));
            }

            @Override
            protected void onBindViewHolder(UserViewHolder viewHolder, int position, final User model) {
                final DatabaseReference postRef = getRef(position);

                // Set click listener for the whole post view
                final String postKey = postRef.getKey();
                if (DemoApplication.mUser.getId().equals(model.getId())) {
                    viewHolder.itemView.setBackgroundColor(getResources().getColor(R.color.gray_dark));
                } else {
                    viewHolder.itemView.setBackgroundColor(getResources().getColor(R.color.white));
                }
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.e("test", "---" + postKey);
                        if (DemoApplication.mUser.getId().equals(model.getId())) {
                            return;
                        }
                        DatabaseReference chats = mDatabase.child("chats").child(DemoApplication.mUser.getId()).child(model.getId());
                        chats.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
//                                String messageKey;
                                long deleteTime = 0;
                                Dialog dialog = dataSnapshot.getValue(Dialog.class);
                                if (dialog != null && dialog.getChatId() != null) {
//                                    messageKey = dialog.getChatId();
                                    deleteTime = dialog.deleteTimestamp;
                                } else {
//                                    messageKey = FirebaseDatabase.getInstance().getReference()
//                                            .child("messages").push().getKey();
                                }
                                Intent intent = new Intent(getActivity(), CustomHolderMessagesActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable(CustomHolderMessagesActivity.EXTRA_USER, model);
//                                intent.putExtra(CustomHolderMessagesActivity.EXTRA_MESSAGE_KEY, messageKey);
                                intent.putExtra(CustomHolderMessagesActivity.EXTRA_DELETETIME_KEY, deleteTime);
                                intent.putExtras(bundle);
                                startActivity(intent);
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                            }
                        });

                    }
                });
                viewHolder.bindToPost(model);

            }
        };
        mRecycler.setAdapter(mAdapter);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mAdapter != null) {
            mAdapter.startListening();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAdapter != null) {
            mAdapter.stopListening();
        }
    }


    public String getUid() {
        return FirebaseAuth.getInstance().getCurrentUser().getUid();
    }

    public abstract Query getQuery(DatabaseReference databaseReference);

}
